<template>
	<view>
		<!-- 导航栏 -->
		<u-navbar 
			title="培训签到" 
			:auto-back="true"
			:background="{ backgroundColor: '#2979ff' }"
			:title-style="{ color: '#ffffff', fontWeight: '600' }"
		></u-navbar>
		
		<!-- 🔧 认证加载界面 -->
		<view v-if="isAuthLoading" class="auth-loading-container">
			<view class="loading-content">
				<view class="loading-icon-auth">
					<u-loading-icon mode="spinner" size="60" color="#2979ff"></u-loading-icon>
					</view>
				<text class="loading-title">正在验证身份</text>
				<text class="loading-subtitle">{{ isAuthenticated ? '正在加载签到信息...' : '正在跳转到企业微信授权...' }}</text>
				</view>
			<view class="loading-footer">
				<text class="footer-text">© 2025 中山公交集团会议签到系统</text>
						</view>
					</view>

		<!-- 🔧 主要内容区域 -->
		<view v-else class="u-page">
			<!-- 培训信息卡片 -->
			<u-transition 
				mode="zoom" 
				:show="showTransition" 
				:duration="300"
			>
				<view class="training-info-card" v-if="trainingInfo">
					<!-- 培训标题区域 -->
					<view class="training-title-section">
						<text class="training-title">{{ trainingInfo.teach_name }}</text>
						
						<!-- 培训状态标签 -->
						<view class="training-status-tag" :class="{
							'status-not-started': trainingInfo.teach_condition === 0,
							'status-in-progress': trainingInfo.teach_condition === 1,
							'status-finished': trainingInfo.teach_condition === 2
						}" v-if="trainingInfo.teach_condition !== undefined">
							<text class="status-text">{{ getTrainingStatusText(trainingInfo.teach_condition) }}</text>
						</view>
					</view>

					<!-- 培训基本信息区域 -->
					<view class="training-info-section">
						<!-- 时间信息 -->
						<view class="info-row">
							<view class="calendar-icon"></view>
							<text class="info-text">{{ formatTimeRange(trainingInfo.start_time, trainingInfo.end_time) }}</text>
						</view>
						
						<!-- 地点信息 -->
						<view class="info-row" v-if="trainingInfo.teach_address">
							<view class="location-icon"></view>
							<text class="info-text">地点：{{ trainingInfo.teach_address }}</text>
						</view>
						<view class="info-row" v-if="trainingInfo.teach_add && trainingInfo.teach_add !== trainingInfo.teach_address">
							<view class="location-icon"></view>
							<text class="info-text">场地：{{ trainingInfo.teach_add }}</text>
						</view>
						
						<!-- 主持人/讲师信息 -->
						<view class="info-row" v-if="trainingInfo.host">
							<view class="instructor-icon"></view>
							<text class="info-text">主持人：{{ trainingInfo.host }}</text>
						</view>
						
						<!-- 场次信息 -->
						<view class="info-row" v-if="trainingInfo.is_multi_session && trainingInfo.total_sessions">
							<view class="session-icon"></view>
							<text class="info-text">{{ trainingInfo.is_multi_session ? '多场培训' : '单场培训' }} (共{{ trainingInfo.total_sessions }}场)</text>
						</view>
					</view>
					
					<!-- 培训内容区域 - 参考详情页设计 -->
					<view class="content-section" v-if="trainingInfo.teach_content">
						<view class="content-header">
							<text class="content-title">培训内容</text>
						</view>
						<!-- 使用 view 包装富文本内容，支持展开/收起 -->
						<view class="content-wrapper">
							<view 
								:class="['content-container', { 'content-collapsed': !isContentExpanded && isContentLong }]"
							>
								<rich-text 
									class="content-rich-text"
									:nodes="parseRichText(trainingInfo.teach_content)"
								></rich-text>
							</view>
							
							<!-- 展开/收起按钮 -->
							<view 
								v-if="isContentLong" 
								class="content-toggle-btn" 
								@click="toggleContent"
							>
								<text class="toggle-text">{{ isContentExpanded ? '收起' : '展开全部' }}</text>
								<view class="toggle-icon" :class="{ 'expanded': isContentExpanded }">
									<text class="icon-arrow">▼</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-transition>

			<!-- 当前场次信息卡片 -->
			<u-transition 
				mode="zoom" 
				:show="showTransition" 
				:duration="300"
				:custom-style="{ 'transition-delay': '0.1s' }"
			>
				<view class="current-session-card" v-if="currentSession">
					<!-- 场次标题区域 -->
					<view class="session-title-section">
						<text class="session-title">{{ currentSession.session_name || `第${currentSession.session_number}场培训` }}</text>
						<text class="session-subtitle">当前场次</text>
						
						<!-- 场次状态标签 -->
						<view class="session-status-tag" :class="{
							'status-upcoming': currentSession.status === 'pending',
							'status-ongoing': currentSession.status === 'ongoing',
							'status-completed': currentSession.status === 'completed'
						}">
							<text class="status-text">{{ getSessionStatusText(currentSession.status) }}</text>
						</view>
					</view>

					<!-- 场次详细信息 -->
					<view class="session-info-section">
						<view class="info-row" v-if="currentSession.session_date">
							<view class="calendar-icon"></view>
							<text class="info-text">{{ formatSessionDate(currentSession.session_date) }}</text>
						</view>
						<view class="info-row" v-if="currentSession.start_time && currentSession.end_time">
							<view class="time-icon"></view>
							<text class="info-text">{{ formatTimeRange(currentSession.start_time, currentSession.end_time) }}</text>
						</view>
						<view class="info-row" v-if="currentSession.location">
							<view class="location-icon"></view>
							<text class="info-text">{{ currentSession.location }}</text>
						</view>
						<view class="info-row" v-if="currentSession.instructor">
							<view class="instructor-icon"></view>
							<text class="info-text">讲师：{{ currentSession.instructor }}</text>
						</view>
						<view class="info-row" v-if="currentSession.content">
							<view class="content-icon"></view>
							<text class="info-text">内容：{{ currentSession.content }}</text>
						</view>
					<view class="info-row" v-if="trainingInfo && trainingInfo.description">
						<view class="description-icon"></view>
						<text class="info-text">简介：{{ trainingInfo.description }}</text>
					</view>
					<!-- 隐藏时长和签到时间 -->
					<!-- <view class="info-row" v-if="currentSession.duration">
						<view class="duration-icon"></view>
						<text class="info-text">时长：{{ currentSession.duration }}小时</text>
					</view>
					<view class="info-row" v-if="currentSession.sign_time && currentSession.sign_status > 0">
						<view class="signin-icon"></view>
						<text class="info-text">签到时间：{{ formatSignTime(currentSession.sign_time) }}</text>
					</view> -->
					</view>
				</view>
			</u-transition>
			
			<!-- 用户签到状态卡片 -->
			<u-transition 
				mode="slide-up" 
				:show="showTransition" 
				:duration="300"
				:custom-style="{ 'transition-delay': '0.1s' }"
			>
				<view class="user-status-card" v-if="userInfo">
				<view class="card-header">
						<view class="user-avatar">
							<text class="avatar-text">{{ userInfo.name ? userInfo.name.charAt(0) : 'U' }}</text>
					</view>
						<view class="user-info">
							<text class="user-name">{{ userInfo.name }}</text>
							<text class="user-id">工号：{{ userInfo.userid }}</text>
				</view>
						
						<!-- 签到状态盖章 -->
						<view class="sign-status-stamp" v-if="currentSession" :class="{
							'stamp-not-signed': currentSession.sign_status === 0,
							'stamp-signed-in': currentSession.sign_status === 1,
							'stamp-signed-out': currentSession.sign_status === 2,
							'stamp-supplementary': currentSession.sign_status === 3
						}">
							<text>{{ getSignStatusText(currentSession.sign_status) }}</text>
					</view>
				</view>

					<!-- 签到时间信息 -->
					<view class="sign-time-info" v-if="currentSession && currentSession.sign_time">
						<view class="time-item">
							<view class="time-label">签到时间</view>
							<view class="time-value">{{ formatSignTime(currentSession.sign_time) }}</view>
						</view>
					</view>
				</view>
			</u-transition>
			
			<!-- 操作按钮区域 -->
			<u-transition 
				mode="zoom" 
				:show="showTransition" 
				:duration="300"
				:custom-style="{ 'transition-delay': '0.2s' }"
			>
				<view class="action-section">
					<!-- 签到按钮 -->
					<view 
						v-if="currentButtonState.type === 'signin'"
						class="action-button sign-in-btn" 
						@click="handleSignIn"
					>
						<view class="btn-icon">
							<u-icon name="checkmark-circle" size="24" color="#ffffff"></u-icon>
						</view>
						<text class="btn-text">{{ currentButtonState.text }}</text>
					</view>

					<!-- 签退按钮 -->
					<view 
						v-else-if="currentButtonState.type === 'signout'"
						class="action-button sign-out-btn" 
						@click="handleSignOut"
					>
						<view class="btn-icon">
							<u-icon name="close-circle" size="24" color="#ffffff"></u-icon>
						</view>
						<text class="btn-text">{{ currentButtonState.text }}</text>
					</view>
					
					<!-- 已完成状态 -->
					<view 
						v-else-if="currentButtonState.type === 'completed'"
						class="action-button completed-btn"
					>
						<view class="btn-icon">
							<u-icon name="checkmark-circle-fill" size="24" color="#ffffff"></u-icon>
						</view>
						<text class="btn-text">{{ currentButtonState.text }}</text>
					</view>

					<!-- 禁用状态（未到时间/时间已过等） -->
					<view 
						v-else
						class="action-button disabled-btn"
					>
						<view class="btn-icon">
							<u-icon name="clock" size="24" color="#ffffff"></u-icon>
						</view>
						<text class="btn-text">{{ currentButtonState.text }}</text>
					</view>
				</view>
			</u-transition>
			
			<!-- 其他场次预览 -->
			<u-transition 
				mode="slide-up" 
				:show="showTransition" 
				:duration="300"
				:custom-style="{ 'transition-delay': '0.3s' }"
			>
				<view class="other-sessions" v-if="otherSessions.length > 0">
					<view class="section-title">
						<text class="title-text">其他场次</text>
						<text class="title-count">{{ otherSessions.length }}场</text>
			</view>
					
					<view class="sessions-list">
						<view 
							v-for="(session, index) in otherSessions" 
							:key="session.id"
							class="session-item"
							:class="{
								'session-completed': session.status === 'completed',
								'session-upcoming': session.status === 'pending'
							}"
						>
							<view class="session-number">{{ session.session_number }}</view>
							<view class="session-content">
								<text class="session-name">{{ session.session_name || `第${session.session_number}场` }}</text>
								<text class="session-time">{{ formatSessionTime(session.start_time, session.end_time) }}</text>
					</view>
							<view class="session-status">
								<text class="status-text">{{ getSessionStatusText(session.status) }}</text>
					</view>
					</view>
			</view>
		</view>
			</u-transition>
			
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<u-loading-icon :show="loading" color="#2979ff" size="28"></u-loading-icon>
				<text class="loading-text">正在加载签到信息...</text>
			</view>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex'
import authMixin from '@/mixins/authMixin.js'

export default {
	name: 'TrainingSignIn',
	mixins: [authMixin],
	data() {
		return {
			teachId: '', // 培训ID
			trainingInfo: null, // 培训基本信息
			currentSession: null, // 当前应该签到的场次
			otherSessions: [], // 其他场次
			loading: false,
			showTransition: false,
			isAuthLoading: true, // 🎯 认证加载状态
			isContentExpanded: false, // 培训内容是否展开
			isContentLong: false, // 培训内容是否过长
			contentMaxLength: 200, // 内容长度阈值（字符数）
			// 🎯 需求二：状态锁定
			signInCompleted: false, // 签到完成标记
			signOutCompleted: false, // 签退完成标记
			preventActions: false // 防止重复操作
		}
	},
	
	computed: {
		// 🎯 获取认证状态
		...mapGetters(['isAuthenticated']),
		
		// 用户信息
		userInfo() {
			return {
				userid: this.$store.getters.userid,
				name: this.$store.getters.empname
			};
		},
		
		// 是否可以签到
		canSignIn() {
			if (!this.currentSession) return false;
			// 直接使用后端返回的权限判断
			return this.currentSession.can_sign_in === true;
		},
		
		// 是否可以签退
		canSignOut() {
			if (!this.currentSession) return false;
			// 直接使用后端返回的权限判断
			return this.currentSession.can_sign_out === true;
		},
		
		// 是否已完成
		isCompleted() {
			if (!this.currentSession) return false;
			return this.currentSession.sign_status === 2 || this.currentSession.status === 'completed';
		},
		
		// 获取当前状态和按钮文本
		currentButtonState() {
			if (!this.currentSession) return { type: 'disabled', text: '加载中...' };
			
			const now = new Date().getTime() / 1000; // 转换为秒
			const startTime = this.currentSession.start_time;
			const endTime = this.currentSession.end_time;
			const signStatus = this.currentSession.sign_status;
			
			// 时间窗口定义
			const signInStartWindow = 30 * 60; // 签到开始前30分钟
			const signInEndWindow = 60 * 60;   // 签到结束后1小时
			const signOutWindow = 60 * 60;     // 签退结束后1小时
			
			// 已签退或培训已结束
			if (signStatus === 2 || this.currentSession.status === 'completed') {
				return { type: 'completed', text: '已完成' };
			}
			
			// 已签到，判断签退条件
			if (signStatus === 1) {
				const signOutStartDelay = 30 * 60; // 培训开始后30分钟
				
				// 优先级1：如果培训已结束，直接可以签退
				if (now >= endTime) {
					if (now <= (endTime + signOutWindow)) {
						return { type: 'signout', text: '签退' };
					} else {
						return { type: 'disabled', text: '签退时间已过' };
					}
				}
				
				// 优先级2：如果培训未结束，则培训开始30分钟后可以签退
				if (now >= (startTime + signOutStartDelay)) {
					return { type: 'signout', text: '签退' };
				} else {
					return { type: 'disabled', text: '未到签退时间' };
				}
			}
			
			// 未签到，判断签到条件
			if (signStatus === 0) {
				// 在签到时间窗口内
				if (now >= (startTime - signInStartWindow) && now <= (endTime + signInEndWindow)) {
					return { type: 'signin', text: '签到' };
				}
				// 未到签到时间
				if (now < (startTime - signInStartWindow)) {
					return { type: 'disabled', text: '未到签到时间' };
				}
				// 签到时间已过
				return { type: 'disabled', text: '签到时间已过' };
			}
			
			return { type: 'disabled', text: '未知状态' };
		}
	},
	
	async onLoad(option) {
		console.log('🔍 签到页面加载，参数:', option);
		
		// 🎯 执行直接认证检查
		try {
			const authResult = await this.performDirectAuth();
			console.log('🔍 认证结果:', authResult);
			
			if (authResult && authResult.success) {
				this.isAuthLoading = false;
				
				// 获取培训ID
				this.teachId = option.tid || option.teachId;
				if (!this.teachId) {
					console.error('❌ 缺少培训ID参数');
					uni.showToast({
						title: '参数错误',
						icon: 'error'
					});
					return;
				}
				
				// 加载签到信息
				await this.loadSignInInfo();
			} else {
				// 认证失败，保持加载状态，等待跳转
				console.log('🔍 认证失败，等待跳转到授权页面');
			}
		} catch (error) {
			console.error('❌ 认证过程出错:', error);
			this.isAuthLoading = false;
		}
	},
	
	methods: {
		// 加载签到信息
		async loadSignInInfo() {
			this.loading = true;
			
			try {
				console.log('🔍 开始加载签到信息，培训ID:', this.teachId);
				
				// 调用新的后端接口获取当前应该签到的场次
				const response = await uni.request({
					url: `${this.$store.getters.currentApiBaseUrl}/api.v2/current-session?userid=${this.$store.getters.userid}&tid=${this.teachId}`,
					method: 'GET',
					header: {
						'Content-Type': 'application/json'
					}
				});
				
				console.log('🔍 签到信息响应:', response);
				
				if (response.statusCode === 200 && response.data.code === 0) {
					const data = response.data.data;
					this.trainingInfo = data.training_info;
					this.currentSession = data.current_session;
					this.otherSessions = data.other_sessions || [];
					
					console.log('✅ 签到信息加载成功');
					console.log('- 当前场次:', this.currentSession);
					console.log('- 其他场次:', this.otherSessions);
					
					// 检查培训内容长度
					this.checkContentLength();
					
					// 显示过渡动画
					this.$nextTick(() => {
						this.showTransition = true;
					});
				} else {
					throw new Error(response.data?.message || '加载签到信息失败');
				}
				
			} catch (error) {
				console.error('❌ 加载签到信息失败:', error);
				uni.showToast({
					title: error.message || '加载失败',
					icon: 'error'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 处理签到
		async handleSignIn() {
			// 🎯 需求二：防止重复操作和误操作
			if (this.preventActions || this.signInCompleted) {
				console.log('🔍 签到操作被阻止：preventActions=', this.preventActions, 'signInCompleted=', this.signInCompleted);
				return;
			}
			
			this.preventActions = true;
			
			try {
				console.log('🔍 开始签到');
				
				const response = await uni.request({
					url: `${this.$store.getters.currentApiBaseUrl}/api.v2/sign-in`,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					data: {
						teach_id: this.teachId,
						session_id: this.currentSession.id,
						userid: this.$store.getters.userid,
						name: this.$store.getters.empname
					}
				});
				
				console.log('🔍 签到响应:', response);
				
				if (response.statusCode === 200 && response.data.code === 0) {
					// 🎯 标记签到完成
					this.signInCompleted = true;
					
					uni.showToast({
						title: '签到成功',
						icon: 'success'
					});
					
					// 🎯 需求一：跳转到success页面，携带培训ID
					setTimeout(() => {
						uni.redirectTo({
							url: `/pages/dtest/success?teach_id=${this.teachId}&session_id=${this.currentSession.id}&action=signin&from_signin=true`
						});
					}, 800); // 延迟0.8秒让用户看到成功提示
					
				} else {
					throw new Error(response.data?.message || '签到失败');
				}
				
			} catch (error) {
				console.error('❌ 签到失败:', error);
				uni.showToast({
					title: error.message || '签到失败',
					icon: 'error'
				});
			} finally {
				this.preventActions = false;
			}
		},
		
		// 处理签退
		async handleSignOut() {
			// 🎯 需求二：防止重复操作
			if (this.preventActions || this.signOutCompleted) {
				console.log('🔍 签退操作被阻止：preventActions=', this.preventActions, 'signOutCompleted=', this.signOutCompleted);
				return;
			}
			
			this.preventActions = true;
			
			try {
				console.log('🔍 开始签退');
				
				const response = await uni.request({
					url: `${this.$store.getters.currentApiBaseUrl}/api.v2/sign-out`,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					data: {
						teach_id: this.teachId,
						session_id: this.currentSession.id,
						userid: this.$store.getters.userid,
						name: this.$store.getters.empname
					}
				});
				
				console.log('🔍 签退响应:', response);
				
				if (response.statusCode === 200 && response.data.code === 0) {
					// 🎯 标记签退完成
					this.signOutCompleted = true;
					
					uni.showToast({
						title: '签退成功',
						icon: 'success'
					});
					
					// 🎯 新需求：检查是否是最后一个场次签退且有问卷调查
					const isLastSession = this.currentSession.is_last_session;
					const hasSurvey = this.trainingInfo.has_survey > 0;
					
					console.log('🔍 签退完成，检查问卷条件:', {
						isLastSession,
						hasSurvey,
						surveyId: this.trainingInfo.has_survey
					});
					
					setTimeout(() => {
						if (isLastSession && hasSurvey) {
							// 最后一个场次签退且有问卷，跳转到问卷页面
							console.log('📝 跳转到问卷页面');
							uni.redirectTo({
								url: `/pages/dtest/star?teach_id=${this.teachId}&survey_id=${this.trainingInfo.has_survey}&from_signout=true`
							});
						} else {
							// 正常跳转到成功页面
							console.log('✅ 跳转到成功页面');
							uni.redirectTo({
								url: `/pages/dtest/success?teach_id=${this.teachId}&session_id=${this.currentSession.id}&action=signout&from_signin=true`
							});
						}
					}, 800); // 延迟0.8秒让用户看到成功提示
					
				} else {
					throw new Error(response.data?.message || '签退失败');
				}
				
			} catch (error) {
				console.error('❌ 签退失败:', error);
				uni.showToast({
					title: error.message || '签退失败',
					icon: 'error'
				});
			} finally {
				this.preventActions = false;
			}
		},
		
		// 检查是否在签到时间范围内
		isWithinSignInTime() {
			if (!this.currentSession) return false;
			
			const now = new Date().getTime();
			const startTime = parseInt(this.currentSession.start_time) * 1000;
			const signInWindow = 30 * 60 * 1000; // 30分钟签到窗口
			
			return now >= (startTime - signInWindow) && now <= startTime;
		},
		
		// 获取场次状态文本
		getSessionStatusText(status) {
			const statusMap = {
				'pending': '待开始',
				'ongoing': '进行中',
				'completed': '已结束',
				'cancelled': '已取消'
			};
			return statusMap[status] || '未知';
		},
		
		// 获取签到状态文本
		getSignStatusText(signStatus) {
			const statusMap = {
				0: '未签到',
				1: '已签到',
				2: '已签退',
				3: '补签'
			};
			return statusMap[signStatus] || '未知';
		},
		
		// 格式化场次日期
		formatSessionDate(sessionDate) {
			if (!sessionDate) return '日期待定';
			
			const date = new Date(sessionDate);
			return date.toLocaleDateString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit',
				weekday: 'short'
			});
		},
		
		// 格式化时间范围
		formatTimeRange(startTime, endTime) {
			if (!startTime || !endTime) return '时间待定';
			
			const formatTime = (timestamp) => {
				const date = new Date(parseInt(timestamp) * 1000);
				return date.toLocaleTimeString('zh-CN', {
					hour: '2-digit',
					minute: '2-digit'
				});
			};
			
			return `${formatTime(startTime)} - ${formatTime(endTime)}`;
		},
		
		// 格式化场次时间（简化版）
		formatSessionTime(startTime, endTime) {
			if (!startTime) return '时间待定';
			
			const date = new Date(parseInt(startTime) * 1000);
			return date.toLocaleString('zh-CN', {
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit'
			});
		},
		
		// 格式化签到时间
		formatSignTime(signTime) {
			if (!signTime) return '';
			
			const date = new Date(parseInt(signTime) * 1000);
			return date.toLocaleString('zh-CN', {
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit'
			});
		},
		
		// 格式化时间（timestamp转时分）
		formatTime(timestamp) {
			if (!timestamp) return '--:--';
			const date = new Date(timestamp * 1000);
			const hour = String(date.getHours()).padStart(2, '0');
			const minute = String(date.getMinutes()).padStart(2, '0');
			return `${hour}:${minute}`;
		},
		
		// 获取培训状态文本
		getTrainingStatusText(condition) {
			const status = parseInt(condition);
			switch(status) {
				case 0: return '未开始';
				case 1: return '进行中';
				case 2: return '已结束';
				default: return '';
			}
		},
		
		// 检查培训内容长度
		checkContentLength() {
			if (!this.trainingInfo || !this.trainingInfo.teach_content) {
				this.isContentLong = false;
				return;
			}
			
			// 移除HTML标签，计算纯文本长度
			const originalContent = this.trainingInfo.teach_content;
			const textContent = originalContent
				.replace(/<[^>]*>/g, '') // 移除HTML标签
				.replace(/&[^;]+;/g, '') // 移除HTML实体
				.replace(/\s+/g, ' ') // 合并多个空格
				.trim();
			
			this.isContentLong = textContent.length > this.contentMaxLength;
		},
		
		// 切换内容展开/收起状态
		toggleContent() {
			this.isContentExpanded = !this.isContentExpanded;
		},
		
		// 解析富文本内容
		parseRichText(htmlContent) {
			if (!htmlContent) return [];
			
			// 如果内容已经是HTML格式，直接返回
			if (typeof htmlContent === 'string' && htmlContent.includes('<')) {
				// 清理一些可能的问题标签和样式
				let cleanHtml = htmlContent
					// 移除可能的脚本标签（安全考虑）
					.replace(/<script[^>]*>.*?<\/script>/gi, '')
					// 移除可能的样式标签
					.replace(/<style[^>]*>.*?<\/style>/gi, '')
					// 处理图片标签，添加样式
					.replace(/<img([^>]*)>/gi, '<img$1 style="max-width:100%;height:auto;display:block;margin:10px 0;">')
					// 处理段落标签，添加间距
					.replace(/<p([^>]*)>/gi, '<p$1 style="margin:8px 0;line-height:1.6;">')
					// 处理标题标签
					.replace(/<h([1-6])([^>]*)>/gi, '<h$1$2 style="margin:12px 0 8px 0;font-weight:600;">')
					// 处理列表
					.replace(/<ul([^>]*)>/gi, '<ul$1 style="margin:8px 0;padding-left:20px;">')
					.replace(/<ol([^>]*)>/gi, '<ol$1 style="margin:8px 0;padding-left:20px;">')
					.replace(/<li([^>]*)>/gi, '<li$1 style="margin:4px 0;line-height:1.5;">')
					// 处理链接
					.replace(/<a([^>]*)>/gi, '<a$1 style="color:#2979ff;text-decoration:underline;">')
					// 处理强调文本
					.replace(/<strong([^>]*)>/gi, '<strong$1 style="font-weight:600;">')
					.replace(/<b([^>]*)>/gi, '<b$1 style="font-weight:600;">')
					.replace(/<em([^>]*)>/gi, '<em$1 style="font-style:italic;">')
					// 处理换行
					.replace(/<br\s*\/?>/gi, '<br/>');
				
				return cleanHtml;
			}
			
			// 如果是纯文本，转换为带格式的HTML
			return htmlContent.replace(/\n/g, '<br/>');
		}
	}
}
</script>

<style lang="scss" scoped>
.u-page {
		background-color: #f5f7fa;
	min-height: calc(100vh - 88rpx);
	padding: 20rpx;
}

/* 培训信息卡片 */
.training-info-card {
	background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
	border: 2rpx solid #e8f4ff;
	margin-bottom: 20rpx;
}

.training-title-section {
	padding: 30rpx;
	background: linear-gradient(135deg, #f0f8ff 0%, #ffffff 100%);
	border-bottom: 1rpx solid #e8f4ff;
	position: relative;
}

.training-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #1a1a1a;
	margin-bottom: 8rpx;
	display: block;
}

.training-subtitle {
	font-size: 26rpx;
	color: #666666;
	display: block;
	margin-bottom: 20rpx;
}

.training-status-tag {
	position: absolute;
	top: 30rpx;
	right: 30rpx;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 20rpx;
	font-weight: 500;
}

.training-status-tag.status-not-started {
	background: rgba(144, 147, 153, 0.1);
	color: #909399;
	border: 1rpx solid rgba(144, 147, 153, 0.3);
}

.training-status-tag.status-in-progress {
	background: rgba(64, 158, 255, 0.1);
	color: #409eff;
	border: 1rpx solid rgba(64, 158, 255, 0.3);
}

.training-status-tag.status-finished {
	background: rgba(103, 194, 58, 0.1);
	color: #67c23a;
	border: 1rpx solid rgba(103, 194, 58, 0.3);
}

.training-info-section {
	padding: 24rpx 30rpx;
}

.content-preview {
	cursor: pointer;
	transition: color 0.3s ease;
}

.content-preview:active {
	color: #2979ff;
}

/* 内容区域 - 参考详情页设计 */
.content-section {
	border-top: 1rpx solid #f0f2f5;
	padding: 24rpx;
	background-color: #fafbfc;
}

.content-header {
	margin-bottom: 16rpx;
}

.content-title {
	font-size: 28rpx;
	color: #303133;
	font-weight: 600;
}

/* 富文本内容样式 */
.content-wrapper {
	position: relative;
}

/* 内容容器 - 控制展开/收起 */
.content-container {
	position: relative;
	transition: all 0.3s ease;
}

/* 内容收起状态 */
.content-container.content-collapsed {
	max-height: 150rpx;
	overflow: hidden;
}

/* 渐变遮罩效果 */
.content-container.content-collapsed::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	height: 80rpx;
	background: linear-gradient(transparent, rgba(250, 252, 255, 0.9), #fafbfc);
	pointer-events: none;
	z-index: 1;
}

.content-rich-text {
	font-size: 26rpx;
	color: #606266;
	line-height: 1.6;
	word-wrap: break-word;
	word-break: break-all;
}

/* 展开/收起按钮样式 */
.content-toggle-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 20rpx;
	margin-top: 16rpx;
	background: linear-gradient(135deg, #f0f8ff 0%, #e8f4ff 100%);
	border: 1rpx solid #e8f4ff;
	border-radius: 12rpx;
	cursor: pointer;
	transition: all 0.3s ease;
	user-select: none;
}

.content-toggle-btn:active {
	transform: scale(0.98);
	background: linear-gradient(135deg, #e8f4ff 0%, #d6efff 100%);
}

.toggle-text {
	font-size: 26rpx;
	color: #2979ff;
	font-weight: 500;
	margin-right: 12rpx;
}

.toggle-icon {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 32rpx;
	height: 32rpx;
	background-color: #2979ff;
	border-radius: 50%;
	transition: transform 0.3s ease;
}

.toggle-icon.expanded {
	transform: rotate(180deg);
}

.icon-arrow {
	font-size: 16rpx;
	color: #ffffff;
	line-height: 1;
}

/* 富文本内部元素样式 */
:deep(.content-rich-text) {
	/* 标题样式 */
	h1, h2, h3, h4, h5, h6 {
		color: #303133;
		margin: 20rpx 0 16rpx 0;
		font-weight: 600;
		line-height: 1.4;
	}
	
	h1 { font-size: 36rpx; }
	h2 { font-size: 32rpx; }
	h3 { font-size: 28rpx; }
	h4 { font-size: 26rpx; }
	h5 { font-size: 24rpx; }
	h6 { font-size: 22rpx; }
	
	/* 段落样式 */
	p {
		margin: 16rpx 0;
		line-height: 1.6;
		text-align: justify;
	}
	
	/* 列表样式 */
	ul, ol {
		margin: 16rpx 0;
		padding-left: 40rpx;
	}
	
	li {
		margin: 8rpx 0;
		line-height: 1.5;
	}
	
	/* 强调文本 */
	strong, b {
		font-weight: 600;
		color: #303133;
	}
	
	em, i {
		font-style: italic;
		color: #606266;
	}
	
	/* 链接样式 */
	a {
		color: #2979ff;
		text-decoration: underline;
	}
	
	/* 图片样式 */
	img {
		max-width: 100%;
		height: auto;
		display: block;
		margin: 20rpx auto;
		border-radius: 8rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}
}

/* 当前场次卡片 */
.current-session-card {
	background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
	border: 2rpx solid #e8f4ff;
	margin-bottom: 20rpx;
}

.session-title-section {
	padding: 30rpx;
	background: linear-gradient(135deg, #f0f8ff 0%, #ffffff 100%);
	border-bottom: 1rpx solid #e8f4ff;
	position: relative;
}

.session-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #1a1a1a;
	margin-bottom: 8rpx;
	display: block;
}

.session-subtitle {
	font-size: 26rpx;
	color: #666666;
	display: block;
	margin-bottom: 20rpx;
}

.session-status-tag {
	position: absolute;
	top: 30rpx;
	right: 30rpx;
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 20rpx;
	font-weight: 500;
}

.session-status-tag.status-upcoming {
	background: rgba(144, 147, 153, 0.1);
	color: #909399;
	border: 1rpx solid rgba(144, 147, 153, 0.3);
}

.session-status-tag.status-ongoing {
	background: rgba(64, 158, 255, 0.1);
	color: #409eff;
	border: 1rpx solid rgba(64, 158, 255, 0.3);
}

.session-status-tag.status-completed {
	background: rgba(103, 194, 58, 0.1);
	color: #67c23a;
	border: 1rpx solid rgba(103, 194, 58, 0.3);
}

.session-info-section {
	padding: 24rpx 30rpx;
}

.info-row {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.info-row:last-child {
	margin-bottom: 0;
}

.info-text {
	font-size: 26rpx;
	color: #333333;
	font-weight: 500;
	margin-left: 12rpx;
}

/* 用户状态卡片 */
.user-status-card {
	background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.06);
	border: 2rpx solid #e8f4ff;
	margin-bottom: 20rpx;
}

.card-header {
	display: flex;
	align-items: center;
	padding: 24rpx 30rpx;
	position: relative;
}

.user-avatar {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #2979ff 0%, #1565c0 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.avatar-text {
	font-size: 24rpx;
	color: #ffffff;
	font-weight: 600;
}

.user-info {
	flex: 1;
}

.user-name {
	font-size: 28rpx;
	font-weight: 600;
	color: #303133;
	display: block;
	margin-bottom: 4rpx;
}

.user-id {
	font-size: 24rpx;
	color: #909399;
	display: block;
}

/* 签到状态盖章 */
.sign-status-stamp {
		position: absolute;
	top: 20rpx;
	right: 20rpx;
	font-size: 18rpx;
	font-weight: 700;
	width: 80rpx;
	height: 50rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 6rpx;
	border: 2rpx solid;
	transform: rotate(-12deg);
	opacity: 0.9;
}

.sign-status-stamp.stamp-not-signed {
	color: #909399;
	border-color: #909399;
	background: rgba(144, 147, 153, 0.1);
}

.sign-status-stamp.stamp-signed-in {
	color: #2979ff;
	border-color: #2979ff;
	background: rgba(41, 121, 255, 0.1);
}

.sign-status-stamp.stamp-signed-out {
	color: #67c23a;
	border-color: #67c23a;
	background: rgba(103, 194, 58, 0.1);
}

.sign-status-stamp.stamp-supplementary {
	color: #e6a23c;
	border-color: #e6a23c;
	background: rgba(230, 162, 60, 0.1);
}

.sign-time-info {
	padding: 0 30rpx 24rpx;
	border-top: 1rpx solid #f0f2f5;
}

.time-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16rpx 0;
}

.time-label {
	font-size: 24rpx;
		color: #909399;
	}

.time-value {
	font-size: 26rpx;
		color: #303133;
		font-weight: 500;
}

/* 操作按钮区域 */
.action-section {
	margin: 20rpx 0;
}

.action-button {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 24rpx;
	border-radius: 16rpx;
	margin: 0 20rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

.action-button:active {
	transform: translateY(2rpx) scale(0.98);
}

.btn-icon {
	margin-right: 12rpx;
}

.btn-text {
	font-size: 32rpx;
	font-weight: 600;
	color: #ffffff;
}

.sign-in-btn {
	background: linear-gradient(135deg, #2979ff 0%, #1565c0 100%);
	box-shadow: 0 8rpx 24rpx rgba(41, 121, 255, 0.3);
}

.sign-out-btn {
	background: linear-gradient(135deg, #f56c6c 0%, #e53e3e 100%);
	box-shadow: 0 8rpx 24rpx rgba(245, 108, 108, 0.3);
}

.completed-btn {
	background: linear-gradient(135deg, #67c23a 0%, #52c41a 100%);
	box-shadow: 0 8rpx 24rpx rgba(103, 194, 58, 0.3);
}

.disabled-btn {
	background: linear-gradient(135deg, #c0c4cc 0%, #a8abb2 100%);
	box-shadow: 0 4rpx 12rpx rgba(192, 196, 204, 0.3);
}

/* 其他场次 */
.other-sessions {
	margin-top: 20rpx;
}

.section-title {
		display: flex;
		align-items: center;
	padding: 20rpx 20rpx 16rpx;
}

.title-text {
	font-size: 28rpx;
	font-weight: 600;
	color: #303133;
}

.title-count {
	font-size: 24rpx;
	color: #909399;
	margin-left: 8rpx;
}

.sessions-list {
	background: #ffffff;
	border-radius: 16rpx;
	overflow: hidden;
	margin: 0 20rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
}

.session-item {
		display: flex;
	align-items: center;
	padding: 20rpx 24rpx;
	border-bottom: 1rpx solid #f0f2f5;
}

.session-item:last-child {
	border-bottom: none;
}

.session-number {
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	background: #f0f2f5;
		display: flex;
		align-items: center;
		justify-content: center;
	font-size: 20rpx;
	font-weight: 600;
	color: #606266;
	margin-right: 16rpx;
}

.session-completed .session-number {
	background: rgba(103, 194, 58, 0.1);
	color: #67c23a;
}

.session-upcoming .session-number {
	background: rgba(64, 158, 255, 0.1);
	color: #409eff;
}

.session-content {
	flex: 1;
}

.session-name {
	font-size: 26rpx;
	color: #303133;
		font-weight: 500;
	display: block;
	margin-bottom: 4rpx;
}

.session-time {
	font-size: 22rpx;
	color: #909399;
	display: block;
}

.session-status {
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
	background: #f0f2f5;
}

.session-status .status-text {
	font-size: 20rpx;
	color: #606266;
}

/* 图标样式 - 复用 detail.vue 的图标 */
.calendar-icon, .time-icon, .location-icon, .instructor-icon, .session-icon {
	width: 24rpx;
	height: 24rpx;
	position: relative;
}

.calendar-icon::before {
	content: "";
	position: absolute;
	width: 20rpx;
	height: 18rpx;
	border: 2rpx solid #2979ff;
	border-radius: 4rpx;
	top: 3rpx;
	left: 2rpx;
}

.calendar-icon::after {
	content: "";
	position: absolute;
	width: 8rpx;
	height: 2rpx;
	background-color: #2979ff;
	top: 9rpx;
	left: 8rpx;
	box-shadow: 0 4rpx 0 #2979ff;
}

.time-icon::before {
	content: "";
	position: absolute;
	width: 16rpx;
	height: 16rpx;
	border: 2rpx solid #ff9900;
	border-radius: 50%;
	top: 4rpx;
	left: 4rpx;
}

.time-icon::after {
	content: "";
	position: absolute;
	width: 4rpx;
	height: 1rpx;
	background-color: #ff9900;
	top: 12rpx;
	left: 12rpx;
	transform: rotate(-45deg);
	transform-origin: 0 0;
	box-shadow: 0 -4rpx 0 #ff9900;
}

.location-icon::before {
	content: "";
	position: absolute;
	width: 12rpx;
	height: 12rpx;
	background-color: #f56c6c;
	border-radius: 50%;
	top: 2rpx;
	left: 6rpx;
}

.location-icon::after {
	content: "";
	position: absolute;
	width: 1rpx;
	height: 8rpx;
	background-color: #f56c6c;
	bottom: 2rpx;
	left: 12rpx;
	transform: rotate(-45deg);
}

.instructor-icon::before {
	content: "";
	position: absolute;
	width: 12rpx;
	height: 12rpx;
	background-color: #9c27b0;
	border-radius: 50%;
	top: 2rpx;
	left: 6rpx;
}

.instructor-icon::after {
	content: "";
	position: absolute;
	width: 16rpx;
	height: 8rpx;
	background-color: #9c27b0;
	border-radius: 8rpx 8rpx 0 0;
	bottom: 2rpx;
	left: 4rpx;
}

.clock-icon::before {
	content: "";
	position: absolute;
	width: 20rpx;
	height: 20rpx;
	border: 2rpx solid #19be6b;
	border-radius: 50%;
	top: 4rpx;
	left: 4rpx;
}


.session-icon::before {
	content: "";
	position: absolute;
	width: 20rpx;
	height: 14rpx;
	border: 2rpx solid #e74c3c;
	border-radius: 2rpx;
	top: 3rpx;
	left: 2rpx;
}

.session-icon::after {
	content: "";
	position: absolute;
	width: 12rpx;
	height: 1rpx;
	background-color: #e74c3c;
	top: 8rpx;
	left: 6rpx;
	box-shadow: 0 3rpx 0 #e74c3c;
}


/* 加载状态 */
.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 40rpx;
}

.loading-text {
	font-size: 26rpx;
	color: #606266;
	margin-top: 20rpx;
}

/* 🔧 认证加载界面样式 - 与其他页面保持一致 */
.auth-loading-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(135deg, #f0f8ff 0%, #e8f4ff 100%);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	z-index: 9999;
}

.loading-content {
	background: #ffffff;
	border-radius: 24rpx;
	padding: 60rpx 40rpx;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	display: flex;
	flex-direction: column;
	align-items: center;
	border: 2rpx solid #e8f4ff;
	min-width: 300rpx;
}

.loading-icon-auth {
	margin-bottom: 32rpx;
}

.loading-title {
	font-size: 32rpx;
	color: #303133;
	font-weight: 600;
	margin-bottom: 16rpx;
	text-align: center;
}

.loading-subtitle {
	font-size: 26rpx;
	color: #606266;
	text-align: center;
	line-height: 1.4;
}

.loading-footer {
	position: absolute;
	bottom: 100rpx;
	left: 50%;
	transform: translateX(-50%);
	padding: 20rpx 40rpx;
	background: rgba(255, 255, 255, 0.9);
	border-radius: 40rpx;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.footer-text {
	font-size: 24rpx;
	color: #909399;
	text-align: center;
}
</style>
